import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent {
  myForm: FormGroup;

  constructor(
    private fb: FormBuilder,
    private router: Router,
    private http: HttpClient,
    private authService: AuthService
  ) {
    this.myForm = this.fb.group({
      username: ['', Validators.required],
      password: ['', [Validators.required, Validators.minLength(6)]]
    });
  }

  onSubmit() {
    console.log('Form submitted');
    const loginData = this.myForm.value;

    // 测试账号数据
    const testAccounts = [
      { username: 'seller', password: 'password1', identity: '卖方客户', balance: 1000, lockedBalance: 200 },
      { username: 'sales', password: 'password2', identity: '销售人员', balance: 2000, lockedBalance: 300 },
      { username: 'trader', password: 'password3', identity: '交易员', balance: 3000, lockedBalance: 400 },
      { username: 'buyer', password: 'password4', identity: '买方客户', balance: 4000, lockedBalance: 500 }
    ];

    // 检查是否匹配测试账号
    const account = testAccounts.find(
      acc => acc.username === loginData.username && acc.password === loginData.password
    );

    if (account) {
      console.log('匹配测试账号:', account);

      // 设置账户信息到 AuthService
      const accountInfo = {
        username: account.username,
        balance: account.balance,
        lockedBalance: account.lockedBalance,
        identity: account.identity
      };
      this.authService.setAccountInfo(accountInfo);

      // 跳转到 dashboard 页面
      this.router.navigate(['/dashboard']);
    } else {
      // 如果不是测试账号，发送请求到后端
      this.http.post('http://localhost:8080/login', loginData).subscribe(
        (response: any) => {
          console.log('服务器响应:', response);

          // 如果服务器返回的状态为 success
          if (response.status === 'success') {
            // 设置账户信息到 AuthService
            const accountInfo = {
              username: response.data.username,
              balance: response.data.balance,
              lockedBalance: response.data.lockedBalance,
              identity: response.data.identity
            };
            this.authService.setAccountInfo(accountInfo);

            // 跳转到 dashboard 页面
            this.router.navigate(['/dashboard']);
          } else {
            // 如果登录失败，提示错误信息
            alert('账号或密码错误');
          }
        },
        error => {
          console.error('登录失败:', error);
          alert('登录失败，请稍后重试');
        }
      );
    }
  }
}
